package cn.lg.soar.system.auth.service;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.system.auth.entity.OrgRole;
import cn.lg.soar.system.auth.mapper.OrgRoleMapper;
import cn.lg.soar.system.config.AuthCacheKey;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2022/4/10
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class OrgRoleService extends ServiceImpl<OrgRoleMapper, OrgRole> {

    /**
     * 根据机构获取角色
     * @param orgId
     * @return
     */
    @Cacheable(value = AuthCacheKey.ROLE_ID_BY_ORG, key = "#orgId", cacheManager = "remote")
    public List<Long> getRoleIds(Long orgId) {
        return listObjs(
                Wrappers.<OrgRole>lambdaQuery()
                        .select(OrgRole::getRoleId)
                        .eq(OrgRole::getOrgId, orgId),
                x -> Long.parseLong(x.toString())
        );
    }

    /**
     * 设置机构角色
     * @param orgId
     * @param roleIds
     */
    @Caching(evict = {
            @CacheEvict(value = AuthCacheKey.ROLE_ID_BY_ORG, key = "#orgId", cacheManager = "remote"),
            @CacheEvict(value = AuthCacheKey.ROLE_ID_BY_USER_ALL, allEntries = true)
    })
    @Transactional(rollbackFor = RuntimeException.class)
    public void setOrgRole(Long orgId, Collection<Long> roleIds) {
        // 清空旧值
        clearByOrg(orgId);

        if (CollectionUtils.isEmpty(roleIds)) {
            return;
        }
        // 批量保存新值
        List<OrgRole> collect = roleIds.stream()
                .distinct()
                .map(x -> {
                    OrgRole data = new OrgRole();
                    data.setOrgId(orgId);
                    data.setRoleId(x);
                    return data;
                })
                .collect(Collectors.toList());
        AssertUtil.isTrue(saveBatch(collect), "保存机构角色失败");
    }

    @Caching(evict = {
            @CacheEvict(value = AuthCacheKey.ROLE_ID_BY_ORG, key = "#orgId", cacheManager = "remote"),
            @CacheEvict(value = AuthCacheKey.ROLE_ID_BY_USER_ALL, allEntries = true)
    })
    public void clearByOrg(Long orgId) {
        this.remove(Wrappers.<OrgRole>lambdaQuery().eq(OrgRole::getOrgId, orgId));
    }

    public void clearByRole(Long roleId) {
        this.remove(Wrappers.<OrgRole>lambdaQuery().eq(OrgRole::getRoleId, roleId));
    }
}
